package IO.常见类使用;

import java.io.*;

/**
 * @program: algorithm
 * @description: 序列化与反序列化
 * @author: 陈恩涛
 * @create: 2022-09-15 23:32
 **/
public class SerializableDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 获取当前的classpath  ---F:\学习笔记\algorithm
        System.out.println(System.getProperty("user.dir"));

        A a1 = new A(123, "abc");
        String objectFile = "java_base\\src\\IO\\常见类使用\\测试文件\\b.txt";
        // 使用文件做中间的传递介质，使用字节数组也可以，深拷贝做法
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
        objectOutputStream.writeObject(a1);
        objectOutputStream.close();

        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
        A a2 = (A) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println(a2);
    }
}

class A implements Serializable {
    private int x;
    private String y;

    A(int x, String y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "x = " + x + "  " + "y = " + y;
    }
}
